import { reactive, watch } from 'vue';
import { LocationQuery, useRoute } from 'vue-router';

const useRedirect = () => {
    const state = reactive({
        redirect: '',
        otherQuery: {}
    });
    const route = useRoute();
    function getOtherQuery(query: LocationQuery) {
        return Object.keys(query).reduce((acc, cur) => {
            if (cur !== 'redirect') {
                acc[cur] = query[cur];
            }
            return acc;
        }, {} as LocationQuery);
    }
    watch(
        () => route.query,
        (query: LocationQuery) => {
            if (query) {
                state.redirect = query.redirect?.toString() ?? '';
                state.otherQuery = getOtherQuery(query);
            }
        },
        { immediate: true }
    );
    return state;
};
export default useRedirect;
